package com.atguigu.gmall.order.service.impl;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.HttpClientUtil;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.mapper.OrderDetailMapper;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author sunjipu
 * @create 2020-04-18 16:07
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitService rabbitService;
//    @Override
//    @Transactional
//    public Long saveOrderInfo(OrderInfo orderInfo) {
//        orderInfo.sumTotalAmount();
//        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
//        String outTradeNo = "ATGUIGU" + System.currentTimeMillis() + "" + new Random().nextInt(1000);
//        orderInfo.setOutTradeNo(outTradeNo);
//        orderInfo.setCreateTime(new Date());
//        // 定义为1天
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, 1);
//        orderInfo.setExpireTime(calendar.getTime());
//
//        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
//        // 获取订单明细
//        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
//        StringBuffer tradeBody = new StringBuffer();
//        for (OrderDetail orderDetail : orderDetailList) {
//            tradeBody.append(orderDetail.getSkuName() + " ");
//        }
//        if (tradeBody.toString().length() > 100) {
//            orderInfo.setTradeBody(tradeBody.toString().substring(0, 100));
//        } else {
//            orderInfo.setTradeBody(tradeBody.toString());
//        }
//
//        orderInfoMapper.insert(orderInfo);
//
//        for (OrderDetail orderDetail : orderDetailList) {
//            orderDetail.setId(null);
//            orderDetail.setOrderId(orderInfo.getId());
//            orderDetailMapper.insert(orderDetail);
//            tradeBody.append(orderDetail.getSkuName() + " ");
//        }
//        return orderInfo.getId();
//    }
    @Override
    @Transactional
    public Long saveOrderInfo(OrderInfo orderInfo) {
        // orderInfo
        // 总金额，订单状态，用户Id，第三方交易编号，创建时间，过期时间，进程状态
        orderInfo.sumTotalAmount();
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        String outTradeNo = "ATGUIGU" + System.currentTimeMillis() + "" + new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setCreateTime(new Date());
        // 定义为1天
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        orderInfo.setExpireTime(calendar.getTime());

        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        orderInfoMapper.insert(orderInfo);

        StringBuffer tradeBody = new StringBuffer();
        // 保存订单明细
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setId(null);
            orderDetail.setOrderId(orderInfo.getId());
            orderDetailMapper.insert(orderDetail);

            tradeBody.append(orderDetail.getSkuName()).append(" ");
        }

        //更新支付描述
        orderInfo.setTradeBody(tradeBody.toString());
        orderInfoMapper.updateById(orderInfo);

        //发送延迟队列，如果定时未支付，取消订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_DIRECT_ORDER_CANCEL, MqConst.ROUTING_ORDER_CANCEL, orderInfo.getId(), MqConst.DELAY_TIME);
        // 返回
        return orderInfo.getId();
    }


        @Override
    public String getTradeNo(String userId) {
        // 定义key
        String tradeNoKey = "user:" + userId + ":tradeCode";
        // 定义一个流水号
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(tradeNoKey, tradeNo);
        return tradeNo;
    }

    @Override
    public boolean checkTradeCode(String userId, String tradeCodeNo) {
        // 定义key
        String tradeNoKey = "user:" + userId + ":tradeCode";
        String redisTradeNo = (String) redisTemplate.opsForValue().get(tradeNoKey);
        return tradeCodeNo.equals(redisTradeNo);
    }

    @Override
    public void deleteTradeNo(String userId) {
        // 定义key
        String tradeNoKey = "user:" + userId + ":tradeCode";
        // 删除数据
        redisTemplate.delete(tradeNoKey);
    }

    @Value("${ware.url}")
    private String WARE_URL;

    @Override
    public boolean checkStock(Long skuId, Integer skuNum) {
        // 远程调用http://www.gware.com /hasStock?skuId=10221&num=2
        String result = HttpClientUtil.doGet(WARE_URL + "/hasStock?skuId=" + skuId + "&num=" + skuNum);
        return "1".equals(result);
    }
    //取消订单
    @Override
    public void cancelOrder(String orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        //订单未支付才可以取消  其它状态不可以自动取消
        if(null != orderInfo && OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())){
            orderInfo.setId(Long.parseLong(orderId));
            //订单状态
            orderInfo.setOrderStatus(OrderStatus.CLOSED.name());
            //进度状态
            orderInfo.setProcessStatus(ProcessStatus.CLOSED.name());
            orderInfoMapper.updateById(orderInfo);
        }
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(queryWrapper);

        orderInfo.setOrderDetailList(orderDetailList);
        return orderInfo;
    }

    @Override
    public void updateOrderStatus(OrderInfo orderInfo) {
        //幂等性
        OrderInfo info = orderInfoMapper.selectById(orderInfo);
        if(OrderStatus.UNPAID.name().equals(info.getOrderStatus())){
            info.setOrderStatus(OrderStatus.PAID.name());
            info.setProcessStatus(ProcessStatus.PAID.name());
            orderInfoMapper.updateById(info);
        }


    }


}
